package com.cj.user.controller;

import com.cj.common.config.handerconfig.IgnoreToken;
import com.cj.common.response.Result;
import com.cj.user.entity.SysUserEntity;
import com.cj.user.service.SysCaptchaService;
import com.cj.user.service.SysUserService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysCaptchaService sysCaptchaService;

	/**
	 * 验证码
	 */
	@IgnoreToken
	@GetMapping("/captcha")
	public void captcha(HttpServletResponse response, String uuid) {
		//获取图片验证码
		sysCaptchaService.getCaptcha(response, uuid);
	}

	/**
	 * 登录
	 */
	@IgnoreToken
	@PostMapping("/sys/login")
	public Result login(@RequestBody Map<String, Object> map) {
		boolean captcha = sysCaptchaService.validate(String.valueOf(map.get("uuid")), String.valueOf(map.get("captcha")));
		if(!captcha){
//			return Result.error(Result.CodeMsg.VERIFICATION_CODE_ERROR);
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(String.valueOf(map.get("username")));

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(String.valueOf(map.get("password")), user.getSalt()).toHex())) {
			return Result.error(Result.CodeMsg.ACCOUNT_OR_PASSWORD_ERROR);
		}

		//账号锁定
		if(user.getStatus() == 0){
			return Result.error(Result.CodeMsg.ACCOUNT_IS_LOCKED_ERROR);
		}

		return Result.success(true);
	}

	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/sys/user/info")
	public Result info(@RequestHeader(value = "user") String user){
		return Result.success(sysUserService.info(user));
	}

	/**
	 * 获取table列表
	 */
	@GetMapping("/sys/table/list")
	public Result list(){
		return Result.success(sysUserService.getList());
	}

	/**
	 * 退出
	 */
	@IgnoreToken
	@PostMapping("/sys/logout")
	public Result logout() {
		// 这里还可以存储退出信息
		return Result.success(true);
	}

	/**
	 * 获取部门人员树
	 */
	@GetMapping("/sys/deptUserTree")
	public Result deptUserTree(){
		return Result.success(sysUserService.deptUserTree());
	}
}
